package com.changgou.oauth.controller;

import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieTools;
import com.changgou.oauth.util.CookieUtil;
import com.changgou.util.Result;
import com.changgou.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*****
 * @Author: shenkunlin
 * @Date: 2019/7/7 16:42
 * @Description: com.changgou.oauth.controller
 ****/
@RestController
@CrossOrigin
@RequestMapping(value = "/user")
public class AuthController {

    //客户端ID
    @Value("${auth.clientId}")
    private String clientId;

    //秘钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    //Cookie存储的域名
    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    AuthService authService;
    @Autowired
    HttpServletResponse response;
    @Autowired
        HttpServletRequest request;

        @PostMapping("/login")
        public Result login(String username, String password) {
            if (StringUtils.isEmpty(username)) {
                throw new RuntimeException("用户名不能为空");
            }
            if (StringUtils.isEmpty(password)) {
                throw new RuntimeException("密码不能为空");
            }
            //获取令牌
            AuthToken login = authService.login(username, password, clientId, clientSecret);
            //取出令牌存入cookies
            String accessToken = login.getAccessToken();
            saveCookie(accessToken);
        //登录会话保持
        CookieTools.setCookie(request,response,"Authorization",accessToken,false);
        CookieTools.setCookie(request,response,"cuname",username,false);
        return new Result(true, StatusCode.OK, "登录成功！");
    }

    /***
     * 将令牌存储到cookie
     * @param token
     */
    private void saveCookie(String token) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "Authorization", token, cookieMaxAge, false);
    }
}
